package com.cdwm.mrp.common.tools;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 在线预览
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/8/20
 */
public class ResponseUtil {
    public static void responseBrowser(File file, HttpServletResponse response){
        //下面的是进行响应客户端的测试代码
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            //设置Http响应头告诉浏览器下载这个附件,下载的文件名也是在这里设置的

            System.out.println("file.getName()   >>>"+file.getName());

            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
            // response.setHeader("Content-Disposition", "inline;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
            System.out.println("file.getPath() >>>>>>"+file.getPath());

            OutputStream outputStream = null;

            outputStream = response.getOutputStream();

            byte[] bytes = new byte[2048];
            int len = 0;
            while ((len = fileInputStream.read(bytes))>0){
                outputStream.write(bytes,0,len);
            }
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件响应出错，读写出错");
        }

    }


    public static void onlineReader(File file, HttpServletResponse response){
        if (file.exists()){
            byte[] data = null;
            try {
                response.setHeader("Content-Disposition", "inline;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
                FileInputStream input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);

                response.getOutputStream().write(data);
                input.close();
            } catch (Exception e) {
                System.out.println(e);
            }

        }else{
            System.out.println("文件不存在");
        }
    }
}

